import django_filters
from .models import Book, Category


class BookFilter(django_filters.FilterSet):
    min_price = django_filters.NumberFilter(field_name='price', lookup_expr='gte')
    max_price = django_filters.NumberFilter(field_name='price', lookup_expr='lte')
    min_rating = django_filters.NumberFilter(field_name='reviews__rating', lookup_expr='gte')
    category = django_filters.ModelChoiceFilter(queryset=Category.objects.filter(is_active=True))
    categories = django_filters.ModelMultipleChoiceFilter(
        field_name='categories',
        queryset=Category.objects.filter(is_active=True),
        conjoined=True
    )
    tags = django_filters.ModelMultipleChoiceFilter(
        field_name='tags',
        queryset=Book.tags.through.objects.all(),
        conjoined=False
    )
    author = django_filters.CharFilter(field_name='author', lookup_expr='icontains')
    publisher = django_filters.CharFilter(field_name='publisher', lookup_expr='icontains')
    is_featured = django_filters.BooleanFilter()
    in_stock = django_filters.BooleanFilter(method='filter_in_stock')
    
    class Meta:
        model = Book
        fields = ['min_price', 'max_price', 'min_rating', 'category', 
                 'categories', 'tags', 'author', 'publisher', 
                 'is_featured', 'in_stock']
    
    def filter_in_stock(self, queryset, name, value):
        if value:
            return queryset.filter(stock_quantity__gt=0)
        return queryset.filter(stock_quantity=0)
